<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace app\admin\service;

use library\tools\Data;
use think\Db;

/**
 * 系统消息管理
 * Class Message.
 */
class Message
{
    /**
     * 增加系统消息.
     *
     * @param string $title 消息标题
     * @param string $desc  消息描述
     * @param string $url   访问链接
     * @param string $node  权限节点
     *
     * @return boolean
     */
    public static function add($title, $desc, $url, $node)
    {
        $code = Data::uniqidNumberCode(12);
        $data = ['title' => $title, 'desc' => $desc, 'url' => $url, 'code' => $code, 'node' => $node];

        return false !== Db::name('SystemMessage')->insert($data);
    }

    /**
     * 系统消息状态更新.
     *
     * @param int $code
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     *
     * @return boolean
     */
    public static function set($code)
    {
        $result = Db::name('SystemMessage')->where(['code' => $code, 'read_state' => '0'])->update([
            'read_state' => '1', 'read_at' => date('Y-m-d H:i:s'), 'read_uid' => session('user.id'),
        ]);

        return false !== $result;
    }

    /**
     * 获取消息列表成功
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return array
     */
    public static function gets()
    {
        $where = ['read_state' => '0'];
        $list  = Db::name('SystemMessage')->where($where)->order('id desc')->select();
        foreach ($list as $key => $vo) {
            if (!empty($vo['node']) && !auth($vo['node'])) {
                unset($list[$key]);
            }
        }

        return $list;
    }
}
